package com.hjm.project.terminal.record.service.impl;

import java.text.ParseException;
import java.util.*;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.hjm.common.exception.BusinessException;
import com.hjm.common.utils.DateUtils;
import com.hjm.common.utils.LogUtils;
import com.hjm.common.utils.StringUtils;
import com.hjm.common.utils.security.ShiroUtils;
import com.hjm.common.utils.yh.Utils;
import com.hjm.project.agentInfo.agentInfo.domain.AgentInfo;
import com.hjm.project.agentInfo.agentInfo.mapper.AgentInfoMapper;
import com.hjm.project.formalPos.branchPos.mapper.BranchPosMapper;
import com.hjm.project.terminal.agentTargetInfo.agentTargetInfo.mapper.AgentTargetInfoMapper;
import com.hjm.project.terminal.detail.mapper.TerminalRecordDetailMapper;
import com.hjm.project.terminal.library.domain.TerminalLibrary;
import com.hjm.project.terminal.library.mapper.TerminalLibraryMapper;
import com.hjm.project.terminal.record.domain.TerminalRecord;
import com.hjm.project.terminal.record.mapper.TerminalRecordMapper;
import com.hjm.project.terminal.record.service.ITerminalRecordService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import com.hjm.common.utils.text.Convert;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

/**
 * 终端划拨记录Service业务层处理
 *
 * @author LOVE
 * @date 2020-11-28
 */
@Service
public class TerminalRecordServiceImpl implements ITerminalRecordService {
    @Resource
    private TerminalRecordMapper terminalRecordMapper;      //终端划拨记录
    @Resource
    private AgentInfoMapper agentInfoMapper;                //代理商信息
    @Resource
    private AgentTargetInfoMapper agentTargetInfoMapper;    //档位分配
    @Resource
    private BranchPosMapper branchPosMapper;                //终端分配
    @Resource
    private TerminalRecordDetailMapper detailMapper;        //划拨记录详情
    @Resource
    private TerminalLibraryMapper terminalLibraryMapper;

    /**
     * 查询终端划拨记录
     *
     * @param id 终端划拨记录ID
     * @return 终端划拨记录
     */
    @Override
    public TerminalRecord selectTerminalRecordById(Long id) {
        return terminalRecordMapper.selectTerminalRecordById(id);
    }

    /**
     * 查询终端划拨记录列表
     *
     * @param terminalRecord 终端划拨记录
     * @return 终端划拨记录
     */
    @Override
    public List<TerminalRecord> selectTerminalRecordList(TerminalRecord terminalRecord) {
        return terminalRecordMapper.selectTerminalRecordList(terminalRecord);
    }


    /**
     * 根据划拨台数分配指标
     * @Param []
     * @Return java.lang.Integer
     */
    @Transactional
    public Integer insertTargetCount(TerminalRecord terminalRecord){

        return null;
    }

    /**
     * 新增终端划拨记录
     * posNo excel中的终端编号
     *
     * @param terminalRecord 终端划拨记录
     * @return 结果
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public Map<String, String> insertTerminalRecord(TerminalRecord terminalRecord, List<String> poses,String... orderNo) throws ParseException {
        LogUtils.logInfo("开始行划拨");
        Integer serial = terminalRecordMapper.terminalRecordSerial();
        List<Map> terminalRecordDetails = new ArrayList<>();
        Map terminalRecordMap = new HashMap();
        Map<String, String> result = new HashMap<>(16);
        result.put("code", "00");
        result.put("msg", "操作成功");
        List<Map<String, Object>> terminalLibraryList = new ArrayList<>();
        List<List<String>> sumArrayList = this.getSumArrayList(poses);
        HashMap maps = new HashMap();
        maps.put("posNo", sumArrayList );
        //只有没有申请人的时候 才可进行 状态验证
        if (StringUtils.isEmpty(terminalRecord.getApplyAgentNum())) {
            /*terminalLibraryList = terminalRecordMapper.getTerminalMap(maps);
            if (terminalLibraryList.size() != poses.size()) {
                result.put("code", "01");
                result.put("msg", "终端状态异常，请检查");
                LogUtils.logInfo("终端状态异常，请检查");
                return result;
            }*/
            for (String posno  : poses) {
                TerminalLibrary t = new TerminalLibrary();
                t.setPosno(posno);
                List<TerminalLibrary> terminalLibraries = terminalLibraryMapper.selectTerminalLibraryList(t);
                if (CollectionUtils.isEmpty(terminalLibraries)) {
                    result.put("code", "01");
                    result.put("msg", "当前posno未匹配到机器" + posno);
                    LogUtils.logInfo("当前posno未匹配到机器" + posno);
                    return result;
                }
                TerminalLibrary terminalLibrary = terminalLibraries.get(0);
                if (terminalLibrary.getStatus().intValue() == 1) {
                    result.put("code", "01");
                    result.put("msg", "当前机器已使用" + terminalLibrary.getMachineNum());
                    LogUtils.logInfo("当前机器已使用" + terminalLibrary.getMachineNum());
                    return result;

                }
                Map posInfo = new HashMap();
                posInfo.put("MACHINE_NUM",terminalLibrary.getMachineNum());
                posInfo.put("POSNO",terminalLibrary.getPosno());
                posInfo.put("TYPE",terminalLibrary.getType());
                posInfo.put("MANU_NUM",terminalLibrary.getManuNum());
                posInfo.put("POS_VERSION",terminalLibrary.getPos_version());
                terminalLibraryList.add(posInfo);


            }

        } else {
            terminalLibraryList = terminalRecordMapper.getTerminalMapNostatus(maps);
        }

        List<Map<String, String>> posList = Lists.newArrayList();
        //判断是否存在终端活动
        for (Map<String, Object> map : terminalLibraryList) {
            Map<String, String> branchPos = Maps.newHashMap();
            branchPos.put("machine_num", String.valueOf(map.get("MACHINE_NUM")));
            branchPos.put("posno", String.valueOf(map.get("POSNO")));
            branchPos.put("pos_type", map.get("TYPE").toString());
            branchPos.put("agent_num", terminalRecord.getAgentTarNum());
            branchPos.put("createname", ShiroUtils.getLoginName());
            branchPos.put("act_id", terminalRecord.getActId());
            branchPos.put("act_end", terminalRecord.getEndDate());
            branchPos.put("manu_num", map.get("MANU_NUM").toString());
            branchPos.put("pos_version", map.get("POS_VERSION").toString());
            branchPos.put("sim_fee", terminalRecord.getSimFee());
            branchPos.put("buyer_num", terminalRecord.getAgentTarNum());  //购买人
            //返现对象
            Integer activeType = terminalRecord.getActiveType() == null ? 0 : terminalRecord.getActiveType();
            Integer standardType = terminalRecord.getStandardType() == null ? 0 : terminalRecord.getStandardType();
            Integer flowType = terminalRecord.getFlowType() == null ? 0 : terminalRecord.getFlowType();
            Integer stageStandardType = terminalRecord.getStageStandardType() == null ? 0 : terminalRecord.getStageStandardType();
            Integer serviceType = terminalRecord.getServiceType() == null ? 0 : terminalRecord.getServiceType();
            branchPos.put("active_type", activeType.toString());        //激活
            branchPos.put("standard_type", standardType.toString());     //达标
            branchPos.put("stage_standard_type", stageStandardType.toString());  //阶段
            branchPos.put("flow_type",flowType.toString());   //流量卡
            branchPos.put("service_type",serviceType.toString());   //流量卡

            branchPos.put("sim_fee",terminalRecord.getSim_fee());   //流量卡
            branchPos.put("sim_end",terminalRecord.getSim_end());   //流量卡
            branchPos.put("service_fee",terminalRecord.getService_fee());   //流量卡
            branchPos.put("service_end",terminalRecord.getService_end());   //流量卡

            if (activeType == 0) {
                branchPos.put("act_agent_num", terminalRecord.getAgentTarNum()); //激活返现代理商编号
            } else {
                branchPos.put("act_agent_num", ""); //激活返现代理商编号
            }

            if (standardType == 0) {
                branchPos.put("reach_agent_num", terminalRecord.getAgentTarNum()); //达标返现代理商编号
            } else {
                branchPos.put("reach_agent_num", ""); //达标返现代理商编号
            }

            if (flowType == 0) {
                branchPos.put("flow_agent_num", terminalRecord.getAgentTarNum()); //激活返现代理商编号
            } else {
                branchPos.put("flow_agent_num", ""); //激活返现代理商编号
            }

            if (stageStandardType == 0) {
                branchPos.put("sta_reach_agent_num", terminalRecord.getAgentTarNum()); //激活返现代理商编号
            } else {
                branchPos.put("sta_reach_agent_num", ""); //激活返现代理商编号
            }
            if (serviceType == 0) {
                branchPos.put("service_agent_num", terminalRecord.getAgentTarNum()); //激活返现代理商编号
            } else {
                branchPos.put("service_agent_num", ""); //激活返现代理商编号
            }

            if (orderNo.length > 0) {
             branchPos.put("dq_type", "2"); //自购机
            } else {
             branchPos.put("dq_type", "1");
            }
            posList.add(branchPos);
        }

        List<List<Map<String, String>>> partition = Lists.partition(posList, 500);
        int i = 0;
        for (List<Map<String, String>> mapList : partition) {
            //批量添加branch_pos
            i = terminalRecordMapper.saveBindingPosBatch(mapList);
            if (i > 0) {
                terminalRecordMapper.updateTerminalUse(mapList);
            } else {
                result.put("code", "01");
                result.put("msg", "划拨失败");
                return result;
            }
        }



        terminalRecordMap.put("agent_num", terminalRecord.getAgentTarNum());
        terminalRecordMap.put("poses", poses);
        List<Map<String, Object>> trDetails = terminalRecordMapper.getGiveSNInfo(terminalRecordMap);
        Integer finalSerial = serial;
        trDetails.forEach((k) -> {
            Map terminalRecordDetailsMap = new HashMap();
            terminalRecordDetailsMap.put("machine_num", k.get("MACHINE_NUM"));
            terminalRecordDetailsMap.put("serial", finalSerial);
            terminalRecordDetails.add(terminalRecordDetailsMap);
        });
        //添加划拨记录
        terminalRecordMap.put("agent_tar_num", terminalRecord.getAgentTarNum());
        terminalRecordMap.put("agent_tar_name", terminalRecord.getAgentTarName());
        terminalRecordMap.put("total", terminalRecordDetails.size());
        terminalRecordMap.put("serial", serial);
        terminalRecordMap.put("add_name", ShiroUtils.getLoginName());
        //是否是发货划入
        if (orderNo.length > 0) {
            terminalRecordMap.put("type", "5");
            terminalRecordMap.put("order_no", orderNo[0]);
            terminalRecordMap.put("param", "发货文件划拨");

        } else {
            terminalRecordMap.put("type", "1");
            terminalRecordMap.put("order_no", "0");
            terminalRecordMap.put("param", "自助划拨");

        }
        if (null == ShiroUtils.getSysUser().getObjNo()) {
            terminalRecordMap.put("add_no", "总后台管理员");
        } else {
            terminalRecordMap.put("add_no", ShiroUtils.getSysUser().getObjNo());
        }
        if (terminalRecordDetails.size() > 0) {
            terminalRecordMapper.addTerminalRecord(terminalRecordMap);
            terminalRecordMapper.addBatchTerminalRecordDetails(terminalRecordDetails);
        }

        //线下划拨(总后台划拨称之为线下划拨)
        /*if (orderNo.length == 0) {
            AgentInfo agentInfo = agentInfoMapper.selectAgentInfoById(terminalRecord.getAgentTarNum());

            //先获取当前的代理指标
            Integer norm_num = agentInfo.getNorm_num().intValue();

            //当前指标数
            Integer tempNormNum = -1;
            String  tempNormLevel = null;
            //划拨的台数
            int size = poses.size();
             if(size == 1000){ //一个V7(10个指标)
                tempNormNum = 20;
                tempNormLevel = "V7";
            }

            //如果符合产生指标增加指标记录
            if (tempNormNum != -1) {
                //更新指标数量
                AgentInfo agent = new AgentInfo();
                agent.setAgentNum(terminalRecord.getAgentTarNum());
                agent.setNorm_num(Long.parseLong(String.valueOf(norm_num + tempNormNum)));
                int i1 = agentInfoMapper.updateAgentNorm(agent);

                //更新指标分配记录
                AgentTargetInfo agentTarget = new AgentTargetInfo();
                agentTarget.setSource(1);
                agentTarget.setNormNum(tempNormNum);
                agentTarget.setGrade(tempNormLevel);
                agentTarget.setType("1");
                agentTarget.setOutAgentNum(ShiroUtils.getSysUser().getObjNo());
                agentTarget.setInAgentNum(terminalRecord.getAgentTarNum());
                agentTarget.setPosCount(size);
                agentTarget.setRemark(ShiroUtils.getSysUser().getLoginName());
                int i2 = agentTargetInfoMapper.insertAgentTargetInfo(agentTarget);
                if (i1  <= 0 || i2 <= 0) {
                    throw new BusinessException("划拨失败,请重新划拨");
                }
            }
        }*/

        if (i > 0) {
            Map messMap = new HashMap();
            messMap.put("agent_num", "0");
            messMap.put("title", "终端申请结果通知");
            messMap.put("create_time", Utils.formateDate(0));
            messMap.put("type", "1");
            messMap.put("jg_status", "1");
            messMap.put("icon", "3");
            messMap.put("read", "1");
            messMap.put("content", "您向" + terminalRecord.getAgentTarName() + "提交的划拨申请已" + ("1".equals(result) ? "拒绝" : "通过") + "!");
            terminalRecordMapper.saveAgentApplyInfo(messMap);
        }
        return result;
    }

    /**
     * 新增终端划拨记录
     * posNo excel中的终端编号
     *
     * @param terminalRecord 终端划拨记录
     * @return 结果
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public Map<String, String> insertTerminalRecordSn(TerminalRecord terminalRecord, List<String> poses,String... orderNo) {
        Integer serial = 0;
        List<Map> terminalRecordDetails = new ArrayList<>();
        Map terminalRecordMap = new HashMap();
        Map<String, String> result = new HashMap<>(16);
        result.put("code", "00");
        result.put("msg", "操作成功");
        List<List<String>> sumArrayList = this.getSumArrayList(poses);
        HashMap maps = new HashMap();
        maps.put("posNo", sumArrayList );
        List<Map<String, Object>> terminalLibraryList = terminalRecordMapper.getTerminalMap(maps);
        //List<Map<String, Object>> terminalLibraryList = terminalRecordMapper.getTerminal(poses);
        if (terminalLibraryList.size() != poses.size()) {
            result.put("code", "01");
            result.put("msg", "终端已分配");
            return result;

        }
        List<Map<String, String>> posList = Lists.newArrayList();
        //判断是否存在终端活动
        for (Map<String, Object> map : terminalLibraryList) {
            Map<String, String> branchPos = Maps.newHashMap();
            branchPos.put("machine_num", String.valueOf(map.get("MACHINE_NUM")));
            branchPos.put("posno", String.valueOf(map.get("POSNO")));
            branchPos.put("pos_type", String.valueOf(map.get("TYPE")));
            branchPos.put("agent_num", terminalRecord.getAgentTarNum());
            branchPos.put("createname", ShiroUtils.getLoginName());
            branchPos.put("act_id", terminalRecord.getActId());
            branchPos.put("act_end", terminalRecord.getEndDate());
            branchPos.put("buyer_num", terminalRecord.getAgentTarNum());
            branchPos.put("manu_num", map.get("MANU_NUM").toString());

            //返现对象
            Integer activeType = terminalRecord.getActiveType();
            Integer standardType = terminalRecord.getStandardType();
            Integer flowType = terminalRecord.getFlowType();
            Integer stageStandardType = terminalRecord.getStageStandardType();
            Integer serviceType = terminalRecord.getServiceType();
            branchPos.put("active_type", activeType.toString());        //激活
            branchPos.put("standard_type", standardType.toString());     //达标
            branchPos.put("stage_standard_type", stageStandardType.toString());  //阶段
            branchPos.put("flow_type",flowType.toString());   //流量卡
            branchPos.put("serviceType",serviceType.toString());   //流量卡

            if (activeType == 0) {
                branchPos.put("act_agent_num", terminalRecord.getAgentTarNum()); //激活返现代理商编号
            } else {
                branchPos.put("act_agent_num", ""); //激活返现代理商编号
            }

            if (standardType == 0) {
                branchPos.put("reach_agent_num", terminalRecord.getAgentTarNum()); //达标返现代理商编号
            } else {
                branchPos.put("reach_agent_num", ""); //达标返现代理商编号
            }

            if (flowType == 0) {
                branchPos.put("flow_agent_num", terminalRecord.getAgentTarNum()); //激活返现代理商编号
            } else {
                branchPos.put("flow_agent_num", ""); //激活返现代理商编号
            }

            if (stageStandardType == 0) {
                branchPos.put("sta_reach_agent_num", terminalRecord.getAgentTarNum()); //激活返现代理商编号
            } else {
                branchPos.put("sta_reach_agent_num", ""); //激活返现代理商编号
            }
            if (serviceType == 0) {
                branchPos.put("service_agent_num", terminalRecord.getAgentTarNum()); //激活返现代理商编号
            } else {
                branchPos.put("service_agent_num", ""); //激活返现代理商编号
            }



            if (orderNo.length > 0) {
                //添加终端购买人
                branchPos.put("dq_type", "2");  // 1 划拨机  2 //自购机
            } else {
                branchPos.put("dq_type", "1");
            }
            branchPos.put("sim_fee", "0");
            posList.add(branchPos);
        }
        //批量添加branch_pos
        int i = terminalRecordMapper.saveBindingPosBatch(posList);
        if (i > 0) {
            terminalRecordMapper.updateTerminalUse(posList);
        } else {
            result.put("code", "01");
            result.put("msg", "划拨失败");
            return result;

        }
        terminalRecordMap.put("agent_num", terminalRecord.getAgentTarNum());
        terminalRecordMap.put("poses", poses);
        List<Map<String, Object>> trDetails = terminalRecordMapper.getGiveSNInfo(terminalRecordMap);
        serial = terminalRecordMapper.terminalRecordSerial();
        Integer finalSerial = serial;
        trDetails.forEach((k) -> {
            Map terminalRecordDetailsMap = new HashMap();
            terminalRecordDetailsMap.put("machine_num", k.get("MACHINE_NUM"));
            terminalRecordDetailsMap.put("serial", finalSerial);
            terminalRecordDetails.add(terminalRecordDetailsMap);
        });
        //添加划拨记录
        terminalRecordMap.put("agent_tar_num", terminalRecord.getAgentTarNum());
        terminalRecordMap.put("agent_tar_name", terminalRecord.getAgentTarName());
        terminalRecordMap.put("total", terminalRecordDetails.size());
        terminalRecordMap.put("param", "发货SN划拨");
        terminalRecordMap.put("serial", serial);
        terminalRecordMap.put("add_name", ShiroUtils.getLoginName());
        //是否是发货划入
        if (orderNo.length > 0) {
            terminalRecordMap.put("type", "5");
            terminalRecordMap.put("order_no", orderNo[0]);
        } else {
            terminalRecordMap.put("type", "1");

        }
        if (null == ShiroUtils.getSysUser().getObjNo()) {
            terminalRecordMap.put("add_no", "总后台管理员");
        } else {
            terminalRecordMap.put("add_no", ShiroUtils.getSysUser().getObjNo());
        }
        if (terminalRecordDetails.size() > 0) {
            terminalRecordMapper.addTerminalRecord(terminalRecordMap);
            terminalRecordMapper.addBatchTerminalRecordDetails(terminalRecordDetails);
        }
        if (i > 0) {
            Map messMap = new HashMap();
            messMap.put("agent_num", "0");
            messMap.put("title", "终端申请结果通知");
            messMap.put("create_time", Utils.formateDate(0));
            messMap.put("type", "1");
            messMap.put("jg_status", "1");
            messMap.put("icon", "3");
            messMap.put("read", "1");
            messMap.put("content", "您向" + terminalRecord.getAgentTarName() + "提交的划拨申请已" + ("1".equals(result) ? "拒绝" : "通过") + "!");
            terminalRecordMapper.saveAgentApplyInfo(messMap);
            //添加终端划拨(划入)记录
            /*Map map = new HashMap();
            Utils utils = new Utils();
            map.put("agent_tar_num", terminalRecord.getAgentTarNum());//目标服务商
            map.put("agent_tar_name", terminalRecord.getAgentTarName());//目标服务商名称
            map.put("type", "0");
            map.put("total", poses.size());//台数
            map.put("param", "SN连续号段划拨");
            map.put("serial", serial);
            map.put("add_name", ShiroUtils.getLoginName());
            map.put("add_no", "0");
            map.put("add_date", Utils.formateDate(0));
            map.put("add_time", Utils.formateDate(3));
            map.put("agent_apply_id", Utils.formateDate(4));
            map.put("poses", poses);
            //添加终端划拨记录明细
            terminalRecordMapper.insertTerRecordDe(map);
            terminalRecordMapper.insertTerRecord(map);*/
        }
        return result;
    }



    /**
     * 修改终端划拨记录
     *
     * @param terminalRecord 终端划拨记录
     * @return 结果
     */
    @Override
    public int updateTerminalRecord(TerminalRecord terminalRecord) {
        return terminalRecordMapper.updateTerminalRecord(terminalRecord);
    }

    public int updateTerminalRecordCj(TerminalRecord terminalRecord) {
        return terminalRecordMapper.updateTerminalRecordCj(terminalRecord);
    }

    /**
     * 删除终端划拨记录对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteTerminalRecordByIds(String ids) {
        return terminalRecordMapper.deleteTerminalRecordByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除终端划拨记录信息
     *
     * @param id 终端划拨记录ID
     * @return 结果
     */
    @Override
    public int deleteTerminalRecordById(Long id) {
        return terminalRecordMapper.deleteTerminalRecordById(id);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public Map<String, String> addRevoke(TerminalRecord terminalRecord, List<String> posNo, MultipartFile file) throws ParseException {
        Integer serial = 0;
        List<Map> terminalRecordDetails = new ArrayList<>();
        Map terminalRecordMap = new HashMap();
        Map<String, String> result = new HashMap<>(16);
        result.put("code", "00");
        result.put("msg", "操作成功");
        List<List<String>> sumArrayList = this.getSumArrayList(posNo);
        HashMap maps = new HashMap();
        maps.put("posNo", sumArrayList );
        List<Map<String, Object>> terminalLibraryList = terminalRecordMapper.getUseTerminalMap(maps);
        if (terminalLibraryList.size() != posNo.size()) {
            result.put("code", "01");
            result.put("msg", "终端状态异常，请检查");
            return result;
        }

        //查看当前终端是否和终端匹配
        //branchPosMapper.se
        HashMap maps1 = new HashMap();
        maps1.put("posNo", sumArrayList);
        maps1.put("agentNum",terminalRecord.getAgentTarNum());
        maps1.put("activate","2");
        maps1.put("isbound", "0");
        List<Map> maps2 = terminalRecordMapper.selectBranchPosInfo(maps1);
        //获取不到数据
        if (CollectionUtils.isEmpty(maps2)) {
            throw  new BusinessException("未获取到当前服务商的终端信息");
        }

        //查询出的终端和文件终端不匹配,可能是终端不在当前代理身上或者 已使用
        if (maps2.size() != posNo.size()) {
            throw  new BusinessException("请确认终端状态或是否是自己的终端");
        }


        List<Map<String, String>> posList = Lists.newArrayList();
        //判断是否存在终端活动
        for (Map<String, Object> map : terminalLibraryList) {
            Map<String, String> branchPos = Maps.newHashMap();
            branchPos.put("machine_num", String.valueOf(map.get("MACHINE_NUM")));
            branchPos.put("posno", String.valueOf(map.get("POSNO")));
            posList.add(branchPos);
        }


        terminalRecordMap.put("agent_num", terminalRecord.getAgentTarNum());
        terminalRecordMap.put("poses", posNo);
        List<Map<String, Object>> trDetails = terminalRecordMapper.getGiveSNInfo(terminalRecordMap);

        //目标代理最新的撤机记录
        TerminalRecord ter = new TerminalRecord();
        ter.setType("1");
        ter.setAgentTarNum(terminalRecord.getAgentTarNum());
        TerminalRecord record = null;
        List<TerminalRecord> terminalRecords = terminalRecordMapper.selectTerminalRecordList(ter);
        if (CollectionUtils.isEmpty(terminalRecords)){
            result.put("code", "01");
            result.put("msg", "未获取到划拨记录");
            return result;
        } else {
            record = terminalRecords.get(0);
        }


        //查看当前是撤回总公司 还是上级
        AgentInfo agentInfo = agentInfoMapper.selectAgentInfoById(terminalRecord.getAgentTarNum());
        Long belongAgent = agentInfo.getBelongAgent();
        int i = 0;
       // if (belongAgent.toString().equals("100000000") || "0".equals(record.getAddNo())) {
        if (true) {
            Map<String, Object> para = new HashMap<String, Object>();
            para.put("poses", posNo);
            para.put("agent", terminalRecord.getAgentTarNum());
            //删除直签服务商branch_pos 数据
            i = terminalRecordMapper.deleteNextSn(para);
            //将总后台terminal_library数据修改成未分配
            if (i > 0) {
                terminalRecordMapper.updateTerminalNotUse(posList);
            } else {
                result.put("code", "01");
                result.put("msg", "终端撤机失败");
                return result;
            }
        } else {
            result.put("code", "01");
            result.put("msg", "当前服务商不是正式盟主");
            return result;
            /*//修改为上级(逐级撤机)
            HashMap branchParams = new HashMap();
            branchParams.put("posNo", sumArrayList);
            branchParams.put("agentNum", belongAgent);
            branchParams.put("applyAgentNum", terminalRecord.getAgentTarNum());
            branchParams.put("act_agent_num", belongAgent);
            branchParams.put("reach_agent_num",belongAgent);
            int i1 = terminalRecordMapper.updateBranchPosInfo(branchParams);
            if (i1 <= 0) {
                throw  new BusinessException("撤机失败");
            }*/
        }
        serial = terminalRecordMapper.terminalRecordSerial();
        Integer finalSerial = serial;
        trDetails.forEach((k) -> {
            Map terminalRecordDetailsMap = new HashMap();
            terminalRecordDetailsMap.put("machine_num", k.get("MACHINE_NUM"));
            terminalRecordDetailsMap.put("serial", finalSerial);
            terminalRecordDetails.add(terminalRecordDetailsMap);
        });
        //添加划拨记录
        terminalRecordMap.put("agent_tar_num", terminalRecord.getAgentTarNum());
        terminalRecordMap.put("agent_tar_name", terminalRecord.getAgentTarName());
        terminalRecordMap.put("type", "4");
        terminalRecordMap.put("total", terminalRecordDetails.size());
        terminalRecordMap.put("param", "");
        terminalRecordMap.put("serial", serial);
        terminalRecordMap.put("add_name", ShiroUtils.getLoginName());
        terminalRecordMap.put("order_no", DateUtils.dateTimeNow());
        if (null == ShiroUtils.getSysUser().getObjNo()) {
            terminalRecordMap.put("add_no", "总后台管理员");
        } else {
            terminalRecordMap.put("add_no", ShiroUtils.getSysUser().getObjNo());
        }
        if (terminalRecordDetails.size() > 0) {
            terminalRecordMapper.addTerminalRecord(terminalRecordMap);
            terminalRecordMapper.addBatchTerminalRecordDetails(terminalRecordDetails);
        }
        if (i > 0) {
            Map messMap = new HashMap();
            messMap.put("agent_num", "0");
            messMap.put("title", "终端申请结果通知");
            messMap.put("create_time", Utils.formateDate(0));
            messMap.put("type", "1");
            messMap.put("jg_status", "1");
            messMap.put("icon", "3");
            messMap.put("read", "1");
            messMap.put("content", "您向" + terminalRecord.getAgentTarName() + "提交的撤机申请已" + ("1".equals(result) ? "拒绝" : "通过") + "!");
            terminalRecordMapper.saveAgentApplyInfo(messMap);
        }
        return result;
    }



    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public Map<String, String> fhAddRevoke(TerminalRecord terminalRecord, List<String> poses,String orderNo) {
        Integer serial = 0;
        List<Map> terminalRecordDetails = new ArrayList<>();
        Map terminalRecordMap = new HashMap();
        Map<String, String> result = new HashMap<>(16);
        result.put("code", "00");
        result.put("msg", "操作成功");
        //查看终端是否分配
        List<Map<String, Object>> terminalLibraryList = terminalRecordMapper.getUseTerminal(poses);
        if (terminalLibraryList.size() != poses.size()) {
            throw  new BusinessException("终端数据错误");
        }
        List<Map<String, String>> posList = Lists.newArrayList();
        //判断是否存在终端活动
        for (Map<String, Object> map : terminalLibraryList) {
            Map<String, String> branchPos = Maps.newHashMap();
            branchPos.put("machine_num", String.valueOf(map.get("MACHINE_NUM")));
            branchPos.put("posno", String.valueOf(map.get("POSNO")));
            posList.add(branchPos);
        }


        terminalRecordMap.put("agent_num", terminalRecord.getAgentTarNum());
        terminalRecordMap.put("poses", poses);
        List<Map<String, Object>> trDetails = terminalRecordMapper.getGiveSNInfo(terminalRecordMap);

        Map<String, Object> para = new HashMap<String, Object>();
        para.put("poses", poses);
        para.put("agent", terminalRecord.getAgentTarNum());
        //删除直签服务商branch_pos 数据
        int i = terminalRecordMapper.deleteNextSn(para);
        //将总后台terminal_library数据修改成未分配
        if (i > 0) {
            terminalRecordMapper.updateTerminalNotUse(posList);
        } else {
            throw  new BusinessException("终端撤机失败");
        }
        serial = terminalRecordMapper.terminalRecordSerial();
        Integer finalSerial = serial;
        trDetails.forEach((k) -> {
            Map terminalRecordDetailsMap = new HashMap();
            terminalRecordDetailsMap.put("machine_num", k.get("MACHINE_NUM"));
            terminalRecordDetailsMap.put("serial", finalSerial);
            terminalRecordDetails.add(terminalRecordDetailsMap);
        });
        //添加划拨记录
        terminalRecordMap.put("agent_tar_num", terminalRecord.getAgentTarNum());
        terminalRecordMap.put("agent_tar_name", terminalRecord.getAgentTarName());
        terminalRecordMap.put("type", "6");
        terminalRecordMap.put("total", terminalRecordDetails.size());
        terminalRecordMap.put("param", "发货撤机");
        terminalRecordMap.put("serial", serial);
        terminalRecordMap.put("add_name", ShiroUtils.getLoginName());
        terminalRecordMap.put("order_no", orderNo);

        if (null == ShiroUtils.getSysUser().getObjNo()) {
            terminalRecordMap.put("add_no", "总后台管理员");
        } else {
            terminalRecordMap.put("add_no", ShiroUtils.getSysUser().getObjNo());
        }
        if (terminalRecordDetails.size() > 0) {
            int i1 = terminalRecordMapper.addTerminalRecord(terminalRecordMap);
            int i2 = terminalRecordMapper.addBatchTerminalRecordDetails(terminalRecordDetails);
        }
        if (i > 0) {
            Map messMap = new HashMap();
            messMap.put("agent_num", "0");
            messMap.put("title", "终端撤销结果通知");
            messMap.put("create_time", Utils.formateDate(0));
            messMap.put("type", "1");
            messMap.put("jg_status", "1");
            messMap.put("icon", "3");
            messMap.put("read", "1");
            messMap.put("content", "您向" + terminalRecord.getAgentTarName() + "提交的撤机申请已" + ("1".equals(result) ? "拒绝" : "通过") + "!");
            terminalRecordMapper.saveAgentApplyInfo(messMap);
        }
        return result;
    }

    @Override
    public String getPosNoNum(String tempPosNo) {
        String result="0";
        result=terminalRecordMapper.getPosNoNum(tempPosNo);
        return result;
    }



    public <T>  List<List<T>> getSumArrayList(List<T> list){
        List<List<T>> objectlist = new ArrayList<>();
        int iSize = list.size()/1000;
        int iCount = list.size()%1000;
        for(int i=0;i<=iSize;i++){
            List<T> newObjList = new ArrayList<>();
            if(i==iSize){
                for(int j =i*1000;j<i*1000+iCount;j++ ){
                    newObjList.add(list.get(j));
                }
            }else{
                for(int j =i*1000;j<(i+1)*1000;j++ ){
                    newObjList.add(list.get(j));
                }
            }
            if(newObjList.size()>0){
                objectlist.add(newObjList);
            }
        }
        return objectlist;
    }

}
